package CopyOnWriteArrayList_11;
import java.util.concurrent.CopyOnWriteArrayList;
public class 基础用法_多线程安全遍历和修改 {
    public static void main(String[] args) {
        final CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
        list.add("初始元素1");
        list.add("初始元素2");
        final int THREAD_COUNT = 15;
        // 创建10个读取线程
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        // 安全遍历，即使有修改也不会抛出ConcurrentModificationException
                        for (String item : list) {
                            System.out.println(Thread.currentThread().getName() + " 读取: " + item);
                            Thread.sleep((long)(Math.random() * 50)); // 模拟处理时间
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "读取线程-" + i).start();
        }

        // 创建5个写入线程
        for (int i = 0; i < 5; i++) {
            final int elementId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep((long)(Math.random() * 100)); // 随机延迟
                        String newElement = "新元素" + elementId;
                        list.add(newElement);
                        System.out.println(Thread.currentThread().getName() + " 添加: " + newElement);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "写入线程-" + i).start();
        }

        // 等待所有操作完成
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终列表内容: " + list);
    }
}